/**
 * create by young (young2f@outlook.com) on 2020/9/16
 */


'use strict';
import React from 'react';
import {Button, Card, Col, DatePicker, Form, Popconfirm, Row, Select, Statistic, Table, Tabs} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import ViewTitle from "../../../components/ViewTitle";
import {FormField, ModalView, SearchForm} from "antd-extra";
import styles from "../../index.less";
import DescriptionGroup from "../../../components/DescriptionGroup";
import ModalCreateOrEditStatementRecord from "./ModalCreateOrEditStatementRecord";

const {RangePicker} = DatePicker;

const {TabPane} = Tabs;
moment.locale('zh-cn');

@Form.create()
@connect(({
            customer,
            global,
            dict, finance
          }) => ({...global, ...dict, ...customer, ...finance}))
export default class ModalCustomerDetail extends FormBase {
  constructor(props) {
    super(props);
    this.state = {};
  }

  componentDidMount() {
    const {record, dispatch} = this.props;
    const data = this.props.form.getFieldsValue();

    dispatch && dispatch({
      type: 'dict/findMany',
      payload: {type: 'division'}
    });

    dispatch && dispatch({
      type: 'global/getModel',
      payload: {table: 'Customer'}
    });
    const {code} = record;

    this.props.dispatch({
      type: 'customer/findDetail',
      payload: {code, ...data}
    }).then(res => {
      this.setState({...res.result});
    });

    this.props.dispatch({
      type: 'finance/findAccounts',
      payload: {}
    });
  }


  cols = () => {
    return [
      {title: "收入来源", key: "origin", dataIndex: "origin"},
      {title: "收入事由", key: "receiptMatter", dataIndex: "receiptMatter"},
      {title: "收入金额", key: "receiptAmount", dataIndex: "receiptAmount"},
      {title: "销售业务员", key: "receiptSalesman", dataIndex: "receiptSalesman"},
      {title: "收款方式", key: "receiptWay", dataIndex: "receiptWay"},
      {title: "收款银行", key: "openingBank", dataIndex: "openingBank"},
      {title: "收款账号", key: "account", dataIndex: "account"},
      {
        title: "日期", key: "createdTs", dataIndex: "createdTs", render: (text, record) => {
          return <div>{moment(text).format('YYYY-MM-DD')}</div>;
        }
      }
    ];
  };

  getCard(list) {
    return _.map(list, (item) => {
      const {title, value} = item;
      let color = '#0f0';
      color = value > 0 ? '#35f' : color;
      color = value < 0 ? '#f00' : color;
      return <Col span={8}>
        <Card
          onClick={() => {

          }}
        >
          <Statistic
            title={title}
            value={value}
            precision={3}
            valueStyle={{color}}
          />

        </Card>
      </Col>;
    });
  }

  contactCols() {
    return [{
      title: '客户地址',
      dataIndex: 'address',
      key: 'address'
    },
      {
        title: '联系人',
        dataIndex: 'contacts',
        key: 'contacts'
      },
      {
        title: '联系电话',
        dataIndex: 'contactsPhone',
        key: 'contactsPhone'
      },
      {
        title: '职务',
        dataIndex: 'position',
        key: 'position'
      }

    ];
  }

  statementCols() {
    return [{
      title: '对账金额',
      dataIndex: 'amount',
      key: 'amount'
    },
      {
        title: '对账时间',
        dataIndex: 'createdTs',
        key: 'createdTs',
        render: (value, record) => {
          return <div>{moment(value).format('YYYY-MM-DD')}</div>;
        }
      },
      {
        title: '操作',
        dataIndex: 'opt',
        key: 'opt',
        render: (text, record) => {
          return (<span>
            <a style={{marginRight: '6px'}} onClick={() => {
              this.onCreateOrEditStatementAmountRecord(record);
            }}>编辑</a>

            {<Popconfirm
              title="确认删除"
              onConfirm={() => {
                const {recordId} = record;
                this.props.dispatch({
                  type: 'customer/deleteStatementRecord',
                  payload: {recordId}
                }).then((res) => {
                  this.requestReturn(res);
                  this.componentDidMount();
                });
              }}
              okText="是"
              cancelText="否"
            >
              <a>删除</a>
            </Popconfirm>}
          </span>);
        }
      }
    ];
  }

  onCreateOrEditStatementAmountRecord = record => {
    const type = record ? 'customer/updateStatementRecord' : 'customer/createStatementRecord';
    const _record = record ? record : {code: this.props.record.code};
    _record.recordId = record ? record.recordId : "SAR" + moment().format('YYYYMMDDHHmmss');
    ModalView.open(ModalCreateOrEditStatementRecord,
      {
        title: '对帐单',
        width: '920px'
      }, {
        record: _record,
        callback: (payload) => {
          this.props.dispatch({
            type,
            payload
          }).then(res => {
            this.requestReturn(res);
            this.componentDidMount();
          });
        }
      });
  };

  queryStatementRecord = () => {
    const {record} = this.props;
    const data = this.props.form.getFieldsValue();
    const {statementRecordCreatedTs = [this.getSearchStart1Year(),this.getDefaultSearchEndDate()]} = data;

    const {code} = record;
    const payload = {code, createdTs: [...statementRecordCreatedTs]};

    this.props.dispatch({
      type: 'customer/findStatementRecordMany',
      payload
    });
  };

  render() {
    const {form, style, divisionDict, record = {}, statementRecords = [], accounts = []} = this.props;
    const {
      list,
      receiptAmount = 0,
      salesAmount = 0,
      publicFee = 0,
      invoiceAmount = 0,
      payLaborFee = 0,
      payPublicFee = 0,
      outboundAmount = 0,
      laborFee = 0
    } = this.state;
    console.log('statementRecords', statementRecords);
    const {contactList} = record;
    const array = [
      {title: '当期合同额', value: salesAmount},
      {title: '收入', value: receiptAmount},
      {title: '合同未收', value: (salesAmount - receiptAmount)},
      {title: '开票额', value: invoiceAmount},
      {title: '收入', value: receiptAmount},
      {title: '开票未收', value: (invoiceAmount - receiptAmount)},
      {title: '出货商品金额', value: outboundAmount},
      {title: '收入', value: receiptAmount},
      {title: '出货未收', value: (outboundAmount - receiptAmount)},
      {title: '项目奖励', value: laborFee},
      {title: '劳务费已付', value: payLaborFee},
      {title: '劳务费待付', value: (laborFee - payLaborFee)},
      {title: '业务招待费', value: publicFee},
      {title: '业务招待费已付', value: payPublicFee},
      {title: '业务招待费待付', value: (publicFee - payPublicFee)}
    ];
    const labels = [
      {key: "code", label: "客户编码", _type: "string"},
      {key: "name", label: "客户名称", _type: "string"},
      {key: "industry", label: "客户行业", _type: "string"}
    ];
    return (
      <div style={{...style}}>
        <Tabs defaultActiveKey="0" onTabClick={() => {
          this.queryStatementRecord();
        }}>
          <TabPane tab={"详情"} key="0">
            <ViewTitle title={'基础信息'}></ViewTitle>
            <DescriptionGroup labels={labels} values={record}></DescriptionGroup>
            <ViewTitle title={'联系方式列表'}></ViewTitle>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.contactCols()}
              dataSource={contactList}
              scroll={{x: true}}
              pagination={{
                current: this.state.current,
                total: this.state.total,
                showSizeChanger: true,
                onChange: page => {
                  this.state.current = page;
                  this.componentDidMount();
                },
                onShowSizeChange: (current, pageSize) => {
                  this.state.current = 1;
                  this.state.pageSize = pageSize;
                  this.componentDidMount();
                }
              }}
            ></Table>
          </TabPane>
          <TabPane tab="统计" key="1">
            <SearchForm
              style={{marginLeft: '6px', marginRight: '6px'}}
              onSearch={() => {
                this.state.current = 1;
                this.componentDidMount();
              }}
              onReset={this.handleReset}
              cols={3}
              min={6}
              expandText="展开"
              form={form}
            >
              {[
                <FormField
                  label="统计时间"
                  name="createdTs"
                  key={3}
                  initialValue={[this.getSearchStart1Year(), this.getDefaultSearchEndDate()]}
                >
                  <RangePicker allowClear={true}
                    // style={{ width: '150%' }}
                  />
                </FormField>,
                <FormField
                  label="销售公司"
                  name="division"
                  key={1}

                >
                  <Select allowClear placeholder="请选择" style={{width: '100%'}}
                          onChange={value => {
                            this.state.division = value;
                          }}
                  >
                    {this.getDivision(divisionDict)}
                  </Select>
                </FormField>

              ]}
            </SearchForm>
            <Row gutter={24}>
              {this.getCard(array)}
            </Row>

          </TabPane>
          <TabPane tab="收入" key="2">
            <SearchForm
              style={{marginLeft: '6px', marginRight: '6px'}}
              onSearch={() => {
                this.componentDidMount();
              }}
              onReset={this.handleReset}
              cols={3}
              min={6}
              expandText="展开"
              form={form}
            >
              {[
                <FormField
                  label="统计时间"
                  name="createdTs"
                  key={3}
                  initialValue={[this.getSearchStart1Year(), this.getDefaultSearchEndDate()]}
                >
                  <RangePicker allowClear={true}
                    // style={{ width: '150%' }}
                  />
                </FormField>,
                <FormField
                  label="收款账户"
                  name="accountName"
                  key={1}
                >
                  <Select allowClear placeholder="请选择" style={{width: '100%'}}
                          onChange={value => {
                            this.state.accountName = value;
                          }}
                  >
                    {this.getAccount(accounts)}
                  </Select>
                </FormField>

              ]}
            </SearchForm>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.cols()}
              dataSource={list}
              scroll={{x: true}}
              pagination={true}
              //scroll={{ x: 1300 }}
            ></Table>
          </TabPane>
          <TabPane tab={'对帐单'} key={'3'}>
            <ViewTitle title={"对账单列表"}
                       actions={<Button type={'primary'} onClick={() => {
                         this.onCreateOrEditStatementAmountRecord();
                       }}>添加</Button>}
            ></ViewTitle>
            <SearchForm
              style={{marginLeft: '6px', marginRight: '6px'}}
              onSearch={() => {
                this.queryStatementRecord();
              }}
              onReset={this.handleReset}
              cols={3}
              min={6}
              expandText="展开"
              form={form}
            >
              {[
                <FormField
                  label="对账时间"
                  name="statementRecordCreatedTs"
                  key={3}
                  initialValue={[this.getSearchStart1Year(), this.getDefaultSearchEndDate()]}
                >
                  <RangePicker allowClear={true}
                    // style={{ width: '150%' }}
                  />
                </FormField>
              ]}
            </SearchForm>
            <Table
              className={styles.antTable}
              bordered={true}
              columns={this.statementCols()}
              dataSource={statementRecords}
              scroll={{x: true}}
              pagination={{
                current: this.state.current,
                total: this.state.total,
                showSizeChanger: true,
                onChange: page => {
                  this.state.current = page;
                  this.componentDidMount();
                },
                onShowSizeChange: (current, pageSize) => {
                  this.state.current = 1;
                  this.state.pageSize = pageSize;
                  this.componentDidMount();
                }
              }}
            ></Table>
          </TabPane>
        </Tabs>

      </div>

    );
  }
}

